# -*- encoding: utf-8 -*-
from src.ApiTest.Core.operational_db import OperationalDB
from Common.yaml_method import YamlMethod


class ConnectCheck:
    """
    数据库连接测试
    """

    @staticmethod
    def check(db_info):
        """
        连接数据库
        :param db_info: 数据库信息
        :return:
        """
        code = YamlMethod().read_data('code.yaml')['code']
        database_type = db_info['databaseType']

        if database_type == 'mysql':
            # 连接mysql数据库
            sql = "show databases;"
            try:
                data = OperationalDB().sql_return_result(db_info, sql)
                res = {
                    'code': code[0],
                    'message': '连接成功',
                    'data': data
                }
            except Exception as e:
                res = {
                    'code': code[1],
                    'message': '连接失败',
                    'data': e
                }
        elif database_type == 'postgresql':
            # 连接postgresql数据库
            sql = "select * from pg_tables;"
            try:
                data = OperationalDB().sql_return_result(db_info, sql)
                res = {
                    'code': code[0],
                    'message': '连接成功',
                    'data': data
                }
            except Exception as e:
                res = {
                    'code': code[1],
                    'message': '连接失败',
                    'data': e
                }
        else:
            # 连接redis
            connect = OperationalDB().connect_db(db_info)
            r = connect.ping()
            if r is True:
                res = {
                    'code': code[0],
                    'message': '连接成功',
                    'data': r
                }
            else:
                res = {
                    'code': code[1],
                    'message': '连接失败',
                    'data': r
                }

        return res
